package com.longtop.framework.sys.login.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUtil;
import com.longtop.framework.common.Constant;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.MD5Util;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.codeInfo.model.TSysCodeInfo;
import com.longtop.framework.sys.menu.service.MenuService;
import com.longtop.framework.sys.org.model.TSysOrg;
import com.longtop.framework.sys.role.model.TSysRole;
import com.longtop.framework.sys.user.model.TSysUser;
import com.longtop.framework.util.DateUtil;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;
import com.longtop.intelliweb.action.IInitContext;

public class LoginService extends BaseService {

	public static final String BEAN_ID = "loginService";

	/**
	 * 用户登录校验
	 * 
	 * @param loginName
	 *            用户名
	 * @param password
	 *            密码
	 * @param loginType
	 * @param password2
	 *            动态密码
	 * @param request
	 *            request
	 * @return
	 * @throws BaseCheckedException
	 */
	public SessionObject loginCheck(String loginName, String password, String loginType, HttpServletRequest request) throws BaseCheckedException {

		// 根据登入类型+登录名取得用户对象
		String type = "";
		String typeMsg = "";
		if ("1".equals(loginType)) {// 员工号登入
			type = "userId ";
			typeMsg = "员工号";
		} else if ("2".equals(loginType)) {// OA用户名
			type = "loginName";
			typeMsg = " OA用户名";
		} else {// 身份证
			type = "cardNo";
			typeMsg = "身份证";
		}
		List list = this.queryAll("from TSysUser where upper(" + type + ")='" + loginName.toUpperCase() + "'  and status='1'");

		TSysUser user = null;
		TSysOrg sysOrg = null;
		if (list != null && list.size() > 0) {
			user = (TSysUser) list.get(0);
			sysOrg = (TSysOrg) this.get(TSysOrg.class, user.getOrgId());
		}

		if (user == null) {
			throw new BaseCheckedException(typeMsg + "【" + loginName + "】不存在"); // 用户{0}不存在
		}

		// 密码校验
		if (!StringUtil.isExist(CacheUtil.getConfigValueById(Constant.CONFIG_SUPER_PASS), password, ",")) {

			// 验证本系统密码:(MD5)
			if (!MD5Util.jiaMi(password).equals(user.getPassword())) {
				throw new BaseCheckedException("密码错误,请重新登陆！"); // 密码不符
			}
		}

		TSysRole sysRole = (TSysRole) this.get(TSysRole.class, user.getRoleId());

		// 保存用户信息sessionObject
		SessionObject sessionObject = new SessionObject();

		sessionObject.setUserId(user.getUserId());
		sessionObject.setLoginName(user.getLoginName());
		sessionObject.setUserName(user.getUserName());
		sessionObject.setOrgId(user.getOrgId());
		sessionObject.setOrgName(sysOrg.getOrgName());
		sessionObject.setLoginTime(DateUtil.getDateTime());
		sessionObject.setIpAddr(request.getRemoteAddr());
		sessionObject.setRoleId(user.getRoleId());
		sessionObject.setRoleName(sysRole.getRoleName());

		// 扩展字段：
		sessionObject.setDuty(user.getDuty());
		sessionObject.setSex(user.getSex());
		sessionObject.setCardNo(user.getCardNo());
		sessionObject.setCardType(user.getCardType());
		sessionObject.setIsVirtual(user.getIsVirtual());
		sessionObject.setDutyName("");

		// drcbank
		sessionObject.setParentOrgId(sysOrg.getParentOrgId());
		String parentOrgId = "";
		if (sysOrg.getParentOrgId() != null && !"".equals(sysOrg.getParentOrgId())) {
			parentOrgId = sysOrg.getParentOrgId();
		} else {
			parentOrgId = sysOrg.getOrgId();
		}
		sessionObject.setOrgLevel("" + sysOrg.getOrgLevel());
		sessionObject.setOrgLevelCode(sysOrg.getOrgLevelCode());

		TSysOrg sysOrgParent = CacheUtil.getSysOrgByOrgId(parentOrgId);
		sessionObject.setParentOrgName(sysOrgParent.getOrgName());

		List<TSysCodeInfo> dutyList = CacheUtil.getCodeInfoListByCodeTypeId("USER_DUTY");
		for (TSysCodeInfo sysCodeInfo : dutyList) {
			if (sysCodeInfo.getValue().equals(user.getDuty())) {
				sessionObject.setDutyName(sysCodeInfo.getContent());// 设置职务名称
			}
		}

		// 读取首页url HomeUrl
		HashMap hashMap = new HashMap();
		hashMap.put("userId", user.getUserId());
		hashMap.put("roleId", user.getRoleId());
		String homeUrl = "" + this.queryForObjectByIbatis("sysUserSql.getHomeUrl", hashMap);
		sessionObject.setHomeUrl(homeUrl);
		// 当角色为 admin 时， 拥有全部操作权限
		if (Constant.ADMIN.equals(user.getRoleId())) {
			sessionObject.setAuthOperMenuList(this.queryAll("select menuId from TSysMenu order by sortNo asc"));
			sessionObject.setAuthOperFuncList(this.queryAll("select funcId from TSysFunc"));
		} else {
			sessionObject.setAuthOperMenuList(CacheUtil.getAuthOperMenuByRoleId(user.getRoleId()));
			sessionObject.setAuthOperFuncList(CacheUtil.getAuthOperFuncByRoleId(user.getRoleId()));
		}

		return sessionObject;
	}

	/**
	 * 根据用户菜单代码集获取菜单对象列表，用于显示在MenuBar中
	 * 
	 * @param authOperMenuList
	 *            用户菜单代码集
	 * @return 菜单对象列表
	 */
	public List getUserMenu(List authOperMenuList, IInitContext context) {

		// 从内存中读取
		List result = new ArrayList();
		if (authOperMenuList != null) {
			Iterator iterator = authOperMenuList.iterator();

			// 得到所有菜单列表
			MenuService menuService = (MenuService) SpringBeanFactory.getBean(MenuService.BEAN_ID);
			Map map = menuService.getMenuMap();

			Object object;
			while (iterator.hasNext()) {
				object = iterator.next();
				if (map.containsKey(object)) {
					result.add(map.get(object));
				}
			}
		}

		return result;
	}

	/**
	 * 修改用户密码
	 * 
	 * @param userId
	 *            用户ID<br>
	 * @param oldpwd
	 *            旧密码 <br>
	 * @param newPwd
	 *            新密码<br>
	 * @throws BaseCheckedException
	 */
	public void updatePassword(String userId, String oldpwd, String newPwd) throws BaseCheckedException {

		TSysUser user = (TSysUser) this.get(TSysUser.class, userId);
		if (user == null) {
			// 用户不存在
			throw new BaseCheckedException("操作失败：用户【" + userId + "】不存在。");
		}

		// 加密器（默认采用MD5加密器。是否启用及启用何种加密器可在config/spring/intelliwebframework-login-service.xml中进行配置）
		String oldPassword = MD5Util.jiaMi(oldpwd);
		// 密码区分大小写
		if (!user.getPassword().equals(oldPassword)) {
			// 原密码错误
			throw new BaseCheckedException("操作失败：原密码错误。");
		}
		String newPassword = MD5Util.jiaMi(newPwd); // 新密码加密
		user.setPassword(newPassword);

		this.update(user);
	}

	/**
	 * * 首页 切换角色时候， 调用此方法 更新sessionObject
	 * 
	 * @param sessionObject
	 * @param request
	 * @param roleId
	 * @return
	 */
	public SessionObject changeRole(SessionObject sessionObject, HttpServletRequest request, String roleId) {
		TSysRole sysRole = (TSysRole) this.get(TSysRole.class, roleId);

		// 当角色为 admin 时， 拥有全部操作权限
		if (Constant.ADMIN.equals(roleId)) {
			sessionObject.setAuthOperMenuList(this.queryAll("select menuId from TSysMenu order by sortNo asc"));
			sessionObject.setAuthOperFuncList(this.queryAll("select funcId from TSysFunc"));
		} else {
			sessionObject.setAuthOperMenuList(CacheUtil.getAuthOperMenuByRoleId(roleId));
			sessionObject.setAuthOperFuncList(CacheUtil.getAuthOperFuncByRoleId(roleId));
		}

		// 保存用户信息sessionObject
		sessionObject.setRoleId(roleId);
		sessionObject.setRoleName(sysRole.getRoleName());

		// 读取首页url HomeUrl
		HashMap hashMap = new HashMap();
		hashMap.put("userId", sessionObject.getUserId());
		hashMap.put("roleId", roleId);
		String homeUrl = "" + this.queryForObjectByIbatis("sysUserSql.getHomeUrl", hashMap);
		sessionObject.setHomeUrl(homeUrl);

		return sessionObject;
	}
}